import React, { useRef } from 'react';
import { useEventListener, useBoolean } from 'ahooks';
import classNames from 'classnames';
import styles from './index.less';

const Index = (props) => {
  const { children, className, ...rest } = props;

  const [active, { setTrue, setFalse }] = useBoolean(false);

  const wrapperRef = useRef();

  useEventListener('mouseup', setFalse);

  useEventListener('mousemove', (event) => {
    if (active) {
      const wrapper = wrapperRef.current;
      if (wrapper) {
        wrapper.style.width = `${event.clientX - wrapper.getBoundingClientRect().x}px`;
      }
    }
  });

  return (
    <span ref={wrapperRef} className={classNames(styles.wrapper, className)} {...rest}>
      {children}
      <span
        className={styles.line}
        onMouseDown={() => {
          const selection = window.getSelection ? window.getSelection() : document.getSelection();
          if (selection) {
            selection.removeAllRanges();
          }
          setTrue();
        }}
      />
    </span>
  );
};

Index.displayName = 'Pane';
export default Index;
